#include"Socket.hpp"
#include"agreement.pb.h"

#include<sstream>
#include<string>

using namespace SocketModule;

int main(int argc,char *argv[])
{
    if(argc!=3)
    {
        cout<<"client serverip serverport"<<endl;
        return 1;
    }
    SockPtr sock=make_shared<TcpSocket>();
    sock->BuildSocket(SockType::ORDINARY_SOCK);

    uint16_t server_port=stoi(argv[2]);

    sock->Connect(ntohl(inet_addr(argv[1])),server_port);

    while(true)
    {
        cout<<"client# ";
        string out;

        string in;
        getline(cin,out);

        stringstream ss(out);
        int left=0;
        char opera=0;
        int right=0;
        ss>>left;
        ss>>opera;
        ss>>right;
        //构建请求
        Request requ;
        requ.set__left(left);
        requ.set__operator(opera);
        requ.set__right(right);

        //序列化
        requ.SerializeToString(&out);

        //添加报头
        string info=to_string(out.size())+"\r\n";
        info+=out;

        sock->Send(info);


        sock->Recv(in);
        cout<<in<<endl;
        //去除报头
        int pos=in.find("\r\n");
        in=in.substr(pos+2);

        //反序列化
        Response resp;
        resp.ParseFromString(in);
        cout<<"结果："<<resp._result()<<"结果是否可信: "<< resp._is_trust()<<endl;
    }
    return 0;
}